package com.polaris.live.ui.user_space

import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import com.polaris.live.R
import com.polaris.live.adapter.LikeAdapter
import com.polaris.live.common.cacha.CacheUtil
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.mvvm.base2.BaseVbActivity
import com.polaris.live.common.network.parseState
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.constant.UserConst
import com.polaris.live.databinding.ActivityLikeBinding
import com.polaris.live.utils.route.RoutePath
import com.polaris.live.utils.route.Router
import com.polaris.live.viewmodel.UserSpaceViewModel

/**
 * 点赞列表
 *
 * @author Created by 长空 on 2023/11/02/004 11:02
 */
class LikeActivity : BaseVbActivity<UserSpaceViewModel, ActivityLikeBinding>() {

    private val mAdapter: LikeAdapter by lazy {
        LikeAdapter()
    }

    override fun initView(savedInstanceState: Bundle?) {
        mBinding.recyclerView.setEnableRefresh(false)
        mBinding.recyclerView.apply {
            recycler.layoutManager = LinearLayoutManager(context)
            recycler.itemAnimator = null
            attachedAdapter(mAdapter, mViewModel).observe(
                this@LikeActivity,
                mViewModel.likesLiveData
            )
        }

        val likeDate = CacheUtil.getLikeDate(UserManager.getUser().userId.toString())
        mAdapter.setLikeDate(likeDate)

        mAdapter.setOnItemChildClickListener { _, view, position ->
            val item = mAdapter.data[position]

            when (view.id) {
                R.id.iv_avatar -> {
                    Router.builder(RoutePath.USER_SPACE_ACTIVITY)
                        .withInt("page", UserConst.From.MY)
                        .withLong("userId", item.userBasic.userId)
                        .withAny("userBasic", item.userBasic)
                        .navigation(this)
                }
            }
        }

        initObserver()

        mViewModel.onRefresh()
    }

    private fun initObserver() {
        mViewModel.likesLiveData.observe(this) { resultState ->
            parseState(resultState, {
                if (it.list.isNotEmpty()) {
                    CacheUtil.setLikeDate(
                        UserManager.getUser().userId.toString(),
                        mAdapter.data[0].createTime
                    )
                }
            }, {
                ToastGravity.showGravity(it.errorMsg)
            })
        }
    }

}